/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.fjsei.yewu.graphql;

import graphql.schema.DataFetchingEnvironment;
import graphql.schema.GraphQLObjectType;
import org.fjsei.yewu.filter.Uunode;
import org.fjsei.yewu.util.Tool;
import org.springframework.graphql.data.method.annotation.SchemaMapping;


/**通用的ID转换Relay要的GlobalID模式
 * 每一个graphQL的Object对象type都需单独声明一个XxxController implements IdMapper<type> {} 否则Id都无法转换成Relay要的GlobalID的。
 * 注解@SchemaMapping(typeName="User", field="id")可以用在超类上， 但@Controller不能再加上。
 * 若是extends IdMapper继承 public class IdMapper<T extends Uunode> {  } 其实也能做到的。
 * */

public interface IdMapper<T extends Uunode> {
	/*  @SchemaMapping( field="id" )
	 若改 getId(Uunode typeObj ,结果发现 注册是 Uunode.id
	 此刻*.graphqls文件没登记扩展，只能是走默认getId()路子。
	 若指定type就可以：SchemaMapping(typeName="User", field="id" )
		public String getId(Uunode typeObj ,  针对特定typeName
	* */

	@SchemaMapping( field="id" )
	default String getId(T typeObj , DataFetchingEnvironment env) {
		String typeName= ((GraphQLObjectType)env.getParentType()).getName();
		/*只有 用了@BatchMapping注解的接口方法 才会出现在env.getDataLoaderRegistry()中的。
		所以  在注入public String getId(T typeObj , DataFetchingEnvironment env) { 	的情形下：
		就算是 DataLoader<?, ?>  dataLoader = env.getDataLoaderRegistry().getDataLoader("User.id")  实际返回null;   }
		? 可能两个分开的路子。DataLoader可能是统一的POJO提取一类方法; 但是本例这里是针对单一个TypeName;  ? Scalar coercing, UUID转ID方式;
		, typeObj.getId());
		* */
		return Tool.toGlobalId(typeName, typeObj.getId());
	}
}

